package com.stedu.mall.userservice.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stedu.mall.common.bean.Collect;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.CollectService;
import com.stedu.mall.common.service.GoodsService;
import com.stedu.mall.userservice.mapper.CollectMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class CollectServiceImpl implements CollectService {
    @Autowired
    private CollectMapper collectMapper;
    @DubboReference
    private GoodsService goodsService;
    @Override
    public boolean insert(Collect collect) throws SteduException {
        //根据商品id和用户id查询
        if(collectMapper.selectByGoodsIDAndUserId(collect.getUserId(),collect.getGoodsId()) !=null){
            throw new SteduException("商品已收藏,不能被重复收藏");
        }
        //添加

        return collectMapper.insert(collect)==1;
    }

    @Override
    public boolean delete(Integer id, Integer userId) throws SteduException {
        //判断这个收藏是否存在
        Collect collect = collectMapper.selectById(id);
        if(collect == null){
            throw new SteduException("收藏不存在,无法取消收藏");
        }

        //判断这个收藏是否属于当前用户
        if (!collect.getUserId().equals(userId)){
            throw new SteduException("收藏不属于当前用户,无法取消收藏");
        }
        //删除 --取消收藏
        return collectMapper.delete(id)==1;
    }

    @Override
    public Collect selectByGoodsIDAndUserId(Integer userId, Integer goodsId) {
        return collectMapper.selectByGoodsIDAndUserId(userId,goodsId);
    }

    @Override
    public PageInfo<Collect> selectByPage(Integer userId,Integer pageNum, Integer pageSize) {
        //设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        //查询
        List<Collect> collectList = collectMapper.selectByUserId(userId);
        //查询商品信息
        collectList.forEach(collect -> {
            collect.setGoods(goodsService.selectById(collect.getGoodsId()));
        });
        //创建分页对象
        PageInfo<Collect> collectListInfo = new PageInfo<>(collectList);
        return collectListInfo;
    }
}
